package internal

import "net"

func FilterInterfaces(useIpv4 bool) (ifaces []net.Interface, err error) {
	allIfaces, err := net.Interfaces()
	if err != nil {
		return
	}

	for _, iface := range allIfaces {
		// Interface must be up and either support multicast or be a loopback interface.
		if iface.Flags&net.FlagUp == 0 {
			continue
		}
		if iface.Flags&net.FlagLoopback == 0 && iface.Flags&net.FlagMulticast == 0 {
			continue
		}

		addrs, addrsErr := iface.Addrs()
		if addrsErr != nil {
			err = addrsErr
			return
		}

		supported := false
		for j := range addrs {
			addr, ok := addrs[j].(*net.IPNet)
			if !ok {
				continue
			}
			if addr == nil || addr.IP == nil {
				continue
			}

			// An IP can either be an IPv4 or an IPv6 address.
			// Check if the desired familiy is used.
			familiyMatches := (addr.IP.To4() != nil) == useIpv4
			if familiyMatches {
				supported = true
				break
			}
		}

		if supported {
			ifaces = append(ifaces, iface)
		}
	}

	return
}
